#install.packages("ISwR")
library(ISwR)

# 2.1.1 The workspace -----------------------------------------------------

ls()
rm(height, weight)
x <- 1
save.image() # graba el workspace actual en un fichero llamado .RData
rm(list=ls()) # This does not remove variables whose name begins with a dot because they are not listed by ls()
x <- 2
y <- 3
load(".RData") # AÑADE las variables guardadas en el fichero pero no borra las que hay
x # volvemos a tener el 1

# 2.1.2 Textual output ----------------------------------------------------

sink("myfile")
ls()
sink()

# 2.1.3 Scripting ---------------------------------------------------------

rstudio::saveHistory("rHistory")
rstudio::loadHistory("rHistory")
  
# 2.1.4 Getting help ------------------------------------------------------

help(aggregate)
?aggregate
help.search("kendal")
??kendal

# 2.1.5 Packages ----------------------------------------------------------

library(survival)
detach("package:survival")

# 2.1.7 attach and detach -------------------------------------------------

attach(thuesen) #changing a data frame after attaching it will not affect the variables available since attach involves a (virtual) copy operation of the data frame
blood.glucose
search()
detach()
search()

# 2.1.8 subset, transform, and within -------------------------------------

thue2 <- subset(thuesen,blood.glucose<7)
thue2

thue3 <- transform(thuesen,log.gluc=log(blood.glucose))
# el problema de transform es que no se pueden encadenar tratamientos de variables nuevas
thue3

#An alternative to transform is the within function, which can be used like this:
thue4 <- within(thuesen,{
   log.gluc <- log(blood.glucose)
   m <- mean(log.gluc)
   centered.log.gluc <- log.gluc - m
   rm(m)
   })
thue4

# 2.2 The graphics subsystem ----------------------------------------------


# 2.2.1 Plot layout -------------------------------------------------------

x <- runif(50,0,2)
y <- runif(50,0,2)
plot(x, y, main="Main title", sub="subtitle", xlab="x-label", ylab="y-label")
text(0.6,0.6,"text at (0.6,0.6)")
abline(h=.6,v=.6, col = "gray60", lty=3)

for (side in 1:4){
  mtext(-1:4,side=side,at=.7,line=-1:4)
} 
mtext(paste("side",1:4), side=1:4, line=-1,font=2)

# 2.2.2 Building a plot from pieces ---------------------------------------

plot(x, y, type="n", xlab="", ylab="", axes=F) # plot sin ejes, puntos ni textos. PLOT VACIO
points(x,y)
axis(1)
axis(2,at=seq(0.2,1.8,0.2)) # eje configurable, se puede usar para tener ejes con textos en vez de numeros
box(lty=2)
title(main="Main title", sub="subtitle",xlab="x-label", ylab="y-label")


# 2.2.4 Combining plots ---------------------------------------------------

x <- rnorm(100, sd=10)
h <- hist(x, plot=F) # plot=F para que no pinte, solo calcule los valores
ylim <- range(0, h$density, dnorm(0, sd=10))
hist(x, freq=F, ylim=ylim) # freq=F para que el area todal sea = 1
curve(dnorm(x,sd=10), add=T)

# 2.3 R programming -------------------------------------------------------

hist.with.normal <- function(x, xlab=deparse(substitute(x)), breaks=length(x)/10,...)
{
  h <- hist(x, plot=F, breaks=breaks, ...)
  s <- sd(x)
  m <- mean(x)
  ylim <- range(0,h$density,dnorm(0,sd=s))
  hist(x, freq=F, ylim=ylim, xlab=xlab, breaks=breaks, ...)
  curve(dnorm(x,m,s), add=T, col="red")
}
hist.with.normal(rnorm(2000))

# 2.3.1 Flow control ------------------------------------------------------

y <- 12345
x <- y/2
while (abs(x*x-y) > 1e-10){ # bucle que calcula la raiz de un numero
  x <- (x + y/x)/2
} 
x
x^2

y <- c(4, 9, 25)
x <- y/2
repeat{ # el mismo bucle pero de otra manera (con repeat del que se sale con break)
  x <- (x + y/x)/2
  if (all(abs(x*x - y) < 1e-10)) { # la condición tambien vale para vectores
    break
  }
}
x

x <- seq(0, 1,.05)
plot(x, x, ylab="y", type="l")
for ( j in 2:8 ){
  lines(x, x^j, col=j)
}

# 2.3.2 Classes and generic functions -------------------------------------

methods(print)

# 2.4 Data entry ----------------------------------------------------------


# 2.4.1 Reading from a text file ------------------------------------------

write.table(thuesen, "thuesen.txt")
thuesen2 <- read.table("thuesen.txt")

write.table(secretin, "secretin.txt")
secretin2 <- read.table("secretin.txt")

#por defecto, al leer delfichero se crean factores donde corresponda
class(secretin2$time)
# pero no tenemos control sobre el orden de los levels (es alfabetico)
levels(secretin2$time) # aprenderemos a cambiar esto en el chapter 10

# para saber donde se ubica fisicamente un fichero de datos de un paquete:
system.file("rawdata", "thuesen.txt", package="ISwR")

# 2.4.2 Further details on read.table -------------------------------------

# se pueden controlar muchas cosas en read.table:
# Field separator. 
# NA strings.
# Quotes and comments. 
# Unequal field count. 

#read.csv and read.csv2. The former assumes that fields are separated by a comma, and the latter assumes
#                        that they are separated by semicolons but use a comma as the decimal point

# The colClasses argument allows you to bypass the mechanism by explicitly specifying which columns are 
# of which class (the standard classes "character", "numeric", etc., get special treatment). You can also skip
# unwanted columns by specifying "NULL" as the class.


# 2.4.3 The data editor ---------------------------------------------------

aq <- edit(airquality)

# para editar un data frame vacio
dd <- edit(data.frame())

# 2.4.4 Interfacing to other programs -------------------------------------

# tambien podemos leer del clipboard
read.table("clipboard", header=T)


# 2.5 Exercises -----------------------------------------------------------

# 2.1 Describe how to insert a value between two elements of a vector at a
# given position by using the append function (use the help system to find out). Without append, how would you do it?
x <- c(0,1,2,3,5,6,7,8)
x1 <- append(x, 4, after=4)
x1

# sin append:
x2 <- c(x[1:4],4,x[5:length(x)])
x2
identical(x1, x2)

#more generally, to insert v just after index k (the boundary cases require
                                                some care),
v <- 4; k <- 4
i <- seq(along=x)
x3 <- c(x[i <= k], v, x[i > k])
x3
identical(x1,x3)

# 2.2 Write the built-in data set thuesen to a Tab-separated text file with
# write.table. View it with a text editor (depending on your system).
# Change the NA value to . (period), and read the changed file back into R
# with a suitable command. Also try importing the data into other applications
# of your choice and exporting them to a new file after editing. You
# may have to remove row names to make this work.
write.table(thuesen, "thuesen.txt", na=".")
thuesen2 <- read.table("thuesen.txt", na.strings=".")
thuesen2